<template>
  <div class="public_height100 p20 pub_bgColorFFF">
    <div class="table_content hp100">
      <!-- ====== 表格上方的筛选条件 start ======-->
      <div class="table_filter flex_space_between">
        <div class="flex_start ">
          <div class="table_filter_search">
            <el-input v-model="params.commonSearch" class="pub_input pub_input_search" placeholder="搜索供应商名称" clearable @keydown.enter.native="handleSearch" @clear="handleSearch">
              <img slot="prefix" src="@/assets/img/orderManagement/search.png" class="pub_imgSize16" />
            </el-input>
          </div>
          <div class="table_filter_search ml12 flex_start">
            <el-radio-group v-model="params.commonTag" size="small" @input="getDataList">
              <el-radio-button v-for="item in applyOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio-button>
            </el-radio-group>
            <div class=" ml12">
              <el-button type="text" class="public_confirm_btn pub_button" @click="handleSearch"> 搜索 </el-button>
            </div>
          </div>
        </div>
        <div class="flex_start flex_end">
          <div v-if="params.commonTag == 2">
            <el-button type="text" class="w108 pub_button pub_buttonGreen" @click="showDilogBtn('addDialogVisible')">
              <img src="@/assets/img/orderManagement/add.png" alt="添加供应商" />
              <span class="ml5">添加供应商</span>
            </el-button>
          </div>
          <div v-if="params.commonTag == 2 || roleType == 1" class="ml12">
            <el-button type="text" class="w108 pub_button pub_buttonRed" @click="delteDataBtn">
              <img src="@/assets/img/orderManagement/delete.png" alt="批量删除" />
              <span class="ml5">批量删除</span>
            </el-button>
          </div>
          <div v-if="roleType === 1 && params.commonTag == 4" class="ml12">
            <el-button type="text" class="w108 pub_button pub_buttonGreen" @click="batchAuitBtn">
              <span class="ml0">批量审核</span>
            </el-button>
          </div>
          <div v-if="roleType == 1" class="ml12">
            <el-button type="text" class="w108 pub_button" @click="downloadFile">
              <img src="@/assets/img/orderManagement/download.png" alt="下载模板" />
              <span class="ml5">下载模板</span>
            </el-button>
          </div>
          <div v-if="roleType == 1" class="ml12">
            <el-upload ref="upload" class="avatar-uploader" :show-file-list="false" action="#" :on-change="uploadChange" :auto-upload="false">
              <el-button type="text" class="w80 pub_button">
                <img src="@/assets/img/orderManagement/import.png" alt="导入" />
                <span class="ml5">导入</span>
              </el-button>
            </el-upload>
          </div>
        </div>
      </div>
      <!-- ====== 表格上方的筛选条件 end ======-->
      <el-table ref="multipleTable" size="mini" :data="tableData" tooltip-effect="dark" border :height="`calc(100% - ${100 * $f}px)`" class="wp100 mt12" @selection-change="handleSelectionChange">
        <el-table-column v-if="params.commonTag != 1 || roleType == 1" key="selection" type="selection" align="center" :width="`${55 * $f}`" />
        <el-table-column label="序号" type="index" :width="`${50 * $f}`" align="center" />
        <el-table-column key="productSupplierName" label="供应商名称" show-overflow-tooltip prop="productSupplierName" align="center" />
        <el-table-column v-if="params.commonTag != 1 || roleType == 1" key="operation" label="操作" align="center" :width="`${120 * $f}`">
          <template slot-scope="{ row }">
            <el-button v-if="params.commonTag == 2" type="text" class="pub_button public_1EB398_btn" size="mini" @click="editBtnClick(row)">编辑</el-button>
            <el-button v-if="params.commonTag == 2 || roleType == 1" type="text" class="pub_button public_F16363_btn" size="mini" @click="delBtnClick(row)">删除</el-button>
            <el-button v-if="params.commonTag == 4" type="text" class="pub_button public_1EB398_btn" size="mini" @click="auditBtnClick(row)">审核</el-button>
          </template>
        </el-table-column>
        <template slot="empty">
          <PageEmptyData />
        </template>
      </el-table>
      <div ref="pubPageinationRef" class="pub_pageination flex_center mt18">
        <el-pagination background :page-size="params.pageSize" :current-page.sync="params.pageNum" layout="total,prev, pager, next,sizes" :total="params.total" @current-change="changePage" @size-change="changeSize"> </el-pagination>
      </div>
    </div>
    <!-- 删除提示 -->
    <deleteDialog :multiple-selection="multipleSelection" :visible="deleteDialogVisible" @close="closeDialog" @submit="confirmDelete" />
    <!-- 审核提示 -->
    <auditDialog :multiple-selection="multipleSelection" :visible="auditDialogVisible" @close="closeDialog" @submit="confirmAudit" />
    <!-- 添加账户 -->
    <PageDialog :title="addParams.id ? '编辑供应商' : '添加供应商'" :dialog-visible="addDialogVisible" :width="`${$f * 500}px`" @close="closeDialog" @submit="confirmAdd">
      <el-form ref="ruleForm" :model="addParams" :rules="rules" label-width="5rem" class="addOrder">
        <el-form-item label="供应商" prop="productSupplierName">
          <el-input v-model="addParams.productSupplierName" placeholder="请输入供应商" class="pub_input" :maxlength="20" />
        </el-form-item>
      </el-form>
    </PageDialog>
  </div>
</template>
<script>
import tableFun from '@/mixin/tableFun.js';
export default {
  mixins: [tableFun],
  data() {
    return {
      params: { commonSearch: '', commonTag: 1, total: 0, pageSize: 20, pageNum: 1 },
      addParams: {
        productSupplierName: ''
      },
      allInfo: {
        pageFrom: 'productSupplier',
        goodsInfo: {}, //品牌列表页带给上层选它页的信息
        brandInfo: {}, //品牌列表页带给品牌列表页的信息
        stockInfo: {}, //库存信息
        supplierInfo: {}, //供应商信息
        customerInfo: {}, //客户列表往下传的信息
        groupInfo: {}, //课题组往下传的信息
        purchaserInfo: {}, //采购人往下传的信息
        stockDataType: 'add', //库存列表传下来是新增还是编辑
        stockInOrderType: 'add', //订单中库存列表传下来是新增还是编辑
        stockInOrderList: [], //订单中库存列表
        stockInOrderIdx: {}, //订单中库存列表序号
        orderDataType: 'add', //订单列表传下来是新增还是编辑
        unit: '', //计量单位
        id: '' //订单id，编辑时id
      },
      dataListOrg: [],
      curItem: {},
      // 表单验证规则
      rules: {
        productSupplierName: [
          { required: true, message: '请输入供应商', trigger: ['blur', 'change'] },
          { min: 1, max: 20, message: '供应商名称长度不超过20个字符', trigger: ['blur', 'change'] }
        ]
      }
    };
  },
  created() {
    this.getDataList();
  },
  methods: {
    downloadFile() {
      const link = document.createElement('a');
      link.href = '/static/files/供应商导入模板.xlsx'; // 直接放在 public 根目录下
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    // 上传文件
    async uploadChange(file) {
      const form = new FormData();
      form.append('file', file.raw);
      let res = await this.$api.postFile(this.$url.uploadSupplierInfo, form);
      if (res) {
        this.$message({ message: '上传成功', type: 'success' });
        this.params.commonTag = this.roleType == 1 ? 1 : 2;
        this.getDataList();
      } else {
        this.$message.error('上传失败');
      }
    },
    //关闭弹窗
    closeDialog() {
      this.auditDialogVisible = false;
      this.selectedRow = null;
      this.multipleSelection = [];
      this.addDialogVisible = false;
      this.deleteDialogVisible = false;
      this.addParams = Object.assign({}, this.$options.data().addParams); //重置参数
    },
    //获取表格数据
    async getDataList() {
      this.tableData = [];
      let res = await this.$api.get(this.$url.productSupplierPageList, this.params);
      this.tableData = res.rows;
      this.params.total = res.total;
    },
    //确认删除
    async confirmDelete() {
      let res = null;
      if (this.multipleSelection.length > 0 && this.selectedRow === null) {
        let idArr = this.multipleSelection.map(val => val.id);
        res = await this.$api.post(this.$url.productSupplierDeleteBatch, idArr);
      } else {
        res = await this.$api.post(this.$url.productSupplierDelete, { id: this.selectedRow.id });
      }
      this.closeDialog();
      if (res.code === 200) {
        this.$message.success('删除成功');
        this.getDataList();
      } else {
        this.$message.success('删除失败');
      }
    },
    //确认添加
    async confirmAdd() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          let { id } = this.addParams;
          let url = id ? this.$url.productSupplierUpdate : this.$url.productSupplierAdd;
          let res = await this.$api.post(url, this.addParams);
          if (res.code === 200) {
            this.closeDialog();
            this.getDataList();
            this.$message.success(id ? '更新成功' : '新增成功');
          }
        }
      });
    },
    //确认审核
    async confirmAudit() {
      let idArr = [];
      if (this.multipleSelection.length > 0 && this.selectedRow === null) {
        idArr = this.multipleSelection.map(val => val.id);
      } else {
        idArr.push(this.selectedRow.id);
      }
      let res = await this.$api.post(this.$url.productSupplierAudit, idArr);
      this.closeDialog();
      if (res.code === 200) {
        this.$message.success('审核通过');
        this.handleSearch();
      } else {
        this.$message.success('审核失败');
      }
    }
  }
};
</script>